<!--
*@Author: zt
*@Description: 会议新增编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog
    v-bind="$attrs"
    @close="dialogClose"
    @submit="submit"
    :title="$attrs.title"
    :hideBtns="['2', '3'].includes(form['status'] + '') ? ['submit'] : []">
    <a-layout class="f-h-100">
      <a-layout-content
        class="s-bg-white"
        style="overflow: auto">
        <u-flow-tab
          activeKey="1"
          :show="route.params.pType == 2"
          :isAudit="form.status == 2"
          :isAuditPage="route.params.pType == 2"
          :params="{ type: 'meet_apply', ...form, keyid: $attrs.keyid }"
          v-bind="$attrs"
          ref="auditRef">
          <a-tab-pane
            key="1"
            tab="基本信息">
            <a-space
              direction="vertical"
              class="f-w-100">
              <u-busi-card
                title="基本信息"
                :bordered="false">
                <u-form
                  :elements="formEls"
                  :model="form"
                  :gutter="20"
                  ref="formRef"></u-form>
              </u-busi-card>
              <u-busi-card
                title="服务信息"
                :bordered="false">
                <a-form :model="form">
                  <div style="background-color: #fff; padding: 10px 20px; border-radius: 8px">
                    <a-form-item v-if="!form['status'] || ['1', '4'].includes(form['status'] + '')">
                      <div style="color: #1890ff">
                        <span
                          @click="showAddServe = true"
                          style="cursor: pointer">
                          <u-icon-font
                            type="icon-a-tianjiaxinzeng"
                            style="font-size: 12px"></u-icon-font>
                          会议服务新增
                        </span>
                      </div>
                    </a-form-item>
                    <a-form-item
                      label="会议服务"
                      name="会议服务">
                      <a-checkbox-group v-model:value="form.meetserviceArr">
                        <div
                          v-for="(item, index) in meetserviceOptions"
                          :key="index">
                          <a-tooltip
                            placement="topRight"
                            :autoAdjustOverflow="true"
                            color="#fff"
                            style="box-shadow: none">
                            <template #title>
                              <CloseCircleOutlined
                                @click.stop="deletMeetService(item)"
                                style="color: red; cursor: pointer" />
                            </template>
                            <a-checkbox :value="item.value">
                              {{ item.label }}
                              <CloseCircleOutlined
                                @click.stop="deletMeetService(item)"
                                v-if="showItemMeet == item.keyid" />
                            </a-checkbox>
                          </a-tooltip>
                        </div>
                      </a-checkbox-group>
                    </a-form-item>
                  </div>
                </a-form>
              </u-busi-card>
            </a-space>
          </a-tab-pane>
        </u-flow-tab>
      </a-layout-content>
    </a-layout>

    <template #footerBefore>
      <template v-if="!form['status'] || ['1', '4'].includes(form['status'] + '')">
        <u-icon-button
          itype="save"
          @click="submit('up')">
          保存并上报
        </u-icon-button>
      </template>
      <template v-if="route.params.pType == '2' && form['status'] == '2' && isAudited == true">
        <u-icon-button
          itype="approve"
          @click="auditAbout('2')">
          批准
        </u-icon-button>
        <u-icon-button
          itype="close"
          @click="auditAbout('3')">
          退回
        </u-icon-button>
      </template>
    </template>
  </u-dialog>

  <!-- 会议室选择 -->
  <SelMeetRoom
    v-model:open="showSelMeetRoom"
    :startTime="form.starttime"
    :endTime="form.endtime"
    :selectedRowKeys="form.fkconferid ? [form.fkconferid] : []"
    width="70%"
    title="会议室选择"
    @submit="
      ({ rows }) => {
        showSelMeetRoom = false;
        setMeetRoom(rows);
      }
    " />

  <!-- 添加会议服务 -->
  <AddServe
    v-model:open="showAddServe"
    width="20%"
    title="会议服务添加"
    @submit="(showAddServe = false), getMeetServe()"></AddServe>
</template>

<script lang="ts" setup>
import { ref, computed, watch, useAttrs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { _IFormEl, _IExtra } from "@/src/components/common/form/interface";
import { FormInstance, FormItemProps } from "ant-design-vue";
import { _IColumnProps } from "@/components/common/tableEdit/interface.ts";
import { isSel } from "@/common/model/base";
import { storeToRefs } from "pinia";
import { useBaseStore, useLoginStore } from "@/store";
import { cloneDeep } from "lodash";
import { alertC, isValue } from "@/util/common";
import { getItemByIds } from "@/util/format.ts";
import { useAuditAbout } from "@/hooks/useAudit";
import { messageC } from "@/util/common";
import AddServe from "./addServe.vue";
import SelMeetRoom from "./SelMeetRoom.vue";
import dayjs from "dayjs";

import * as AddServeApi from "@/service/administration/meet/addServe/index";
import * as ApplicantApi from "@/service/administration/meet/applicant/index";
import * as travelApi from "@/service/administration/travel";

const attrs = useAttrs();
const emits = defineEmits(["success", "close"]);
const { userInfo } = storeToRefs(useLoginStore());
const { ADV_REPORT_MET } = storeToRefs(useBaseStore());
const route = useRoute();

let auditRef = ref();
const showAddServe = ref(false);
const formRef = ref<FormInstance>();
let meetserviceOptions = ref([]);
let form = ref<any>({
  admTMeetuserList: [],
  conferaddress: "",
  fkconfer: "",
  arrivernumber: 0,
  status: "",
  starttime: "",
  endtime: "",
});

const showItemMeet = ref("");
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: "150px",
  colon: false,
};
const formEls = computed(() => {
  return [
    {
      label: "会议名称",
      key: "meetname",
      col: { span: 24 },
      element: "input",
      formItemProps: { ...formItemProps, required: true },
    },
    {
      label: "会议召集人",
      key: "convenor",
      col: { span: 8 },
      element: "input",
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        disabled: true,
      },
    },
    {
      label: "召集人电话",
      key: "phone",
      col: { span: 8 },
      element: "input",
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        disabled: true,
      },
    },
    {
      label: "会议类型",
      key: "meettype",
      col: { span: 8 },
      element: "select",
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        options: computed(() => ADV_REPORT_MET.value),
      },
    },

    {
      label: "参会人员",
      key: "chry",
      col: { span: 8 },
      element: "selUserTree",
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        disabled: true,
        multiple: true,
        class: "f-normal-disable ",
        fieldNames: { label: "name", value: "keyid" },
      },
    },
    {
      label: "应到人数",
      key: "arrivernumber",
      col: { span: 8 },
      element: "number",
      formItemProps: { ...formItemProps },
      componentProps: {
        disabled: true,
      },
    },
    {
      label: "单位负责人是否参加",
      key: "isincharge",
      col: { span: 8 },
      element: "select",
      formItemProps: { ...formItemProps, required: true },
      componentProps: { options: isSel() },
    },
    {
      label: "会议时间",
      key: "timeRange",
      col: { span: 8 },
      element: "rangePicker",
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        "show-time": true,
        format: "YYYY-MM-DD HH:mm",
        valueFormat: "YYYY-MM-DD HH:mm",
      },
    },

    {
      label: "添加会议室",
      key: "fkconfer",
      col: { span: 8 },
      element: "input",
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        readonly: true,
        onClick: () => {
          if (form.value.timeRange && form.value.timeRange.length > 0) {
            showSelMeetRoom.value = true;
          } else {
            alertC("请先选择会议开始和结束时间");
          }
        },
      },
    },
    {
      label: "会议室地点",
      key: "conferaddress",
      col: { span: 8 },
      element: "input",
      formItemProps: { ...formItemProps },
      componentProps: {
        disabled: true,
      },
    },

    {
      label: "是否短信通知",
      key: "ismessage",
      col: { span: 8 },
      element: "select",
      formItemProps: { ...formItemProps, required: true },
      componentProps: { options: isSel() },
    },

    {
      label: "会议备注",
      key: "remarke",
      col: { span: 24 },
      element: "textarea",
      formItemProps: { ...formItemProps },
    },
    {
      label: "附件",
      key: "appendixSaveVOList",
      col: { span: 24 },
      element: "file",
      formItemProps: { ...formItemProps },
      componentProps: {
        fileParams: { biztype: "4", bucket: "ADM_BIZ_TYPE_MEET" },
      },
    },
  ];
});
const showSelMeetRoom = ref<boolean>(false);

// 会议服务请求
const getMeetServe = async () => {
  let searchF = {
    total: 0,
    current: 1,
    pageSize: 50,
    model: {},
  };
  const res = await AddServeApi.page(searchF);
  if (res.code == 0) {
    const arr = res.data.records;
    arr.map((e) => {
      e.label = e.servicename;
      e.value = e.keyid;
    });
    meetserviceOptions.value = arr;
  }
};

// 获取部门树
const getTree = async () => {
  const res = await travelApi.validTreeApply(userInfo.value["unitId"]);
  if (res.code == 0) {
    const treeData = getItemByIds(res.data, form.value.chry);
    form.value.admTMeetuserList = [];
    treeData.forEach((item) => {
      if (item.children == null) {
        form.value.admTMeetuserList.push({
          userphone: item.exa.tel,
          fkusername: item.name,
          fkuserid: item.keyid,
        });
      }
    });
  }
  form.value.arrivernumber = form.value.admTMeetuserList.length;
};

//删除会议服务
const deletMeetService = async (item) => {
  const res = await AddServeApi.del({ ids: item.keyid });
  if (res.code == 0) {
    alertC(res.msg, "success");
    getMeetServe();
  } else {
    alertC(res.msg, "warning");
  }
};

// 设置会议室的传递数据
const setMeetRoom = (rows) => {
  form.value.fkconfer = rows[0]["name"];
  form.value.conferaddress = rows[0]["address"];
  form.value.fkconferid = rows[0]["keyid"];
};

//保存提交
const submit = async (type?: string) => {
  // if (!form.value.chry) {
  //   alertC('请选择参会人员', 'warning');
  //   return;
  // }

  formRef.value.form.validate().then(async (item) => {
    const url = attrs.keyid ? "update" : "add";
    let copyform = cloneDeep(form.value);
    if (url == "add") {
      copyform["status"] = 1;
    }

    const res = await ApplicantApi[url](copyform);

    if (res.code == 0) {
      if (type != "up") {
        messageC(res.msg, "success");
      }
      if (url == "add") {
        form.value.status = res.data["status"];
        form.value.keyid = res.data["keyid"];
      }
      if (type == "up") {
        await auditAbout("1");
      }
      form.value = {};
      form.value.timeRange = [];
      form.value.appendixSaveVOList = [];
      emits("success");
    } else {
      alertC(res.msg, "warning");
    }
  });
};

// 上报、审核、退回
const auditAbout = async (type: string | number) => {
  const auditParams: IAuditParams = {
    type: "meet_apply",
    selDatas: [form.value],
    confirm: false,
    isDialog: false,
  };
  try {
    // 上报
    const res = await useAuditAbout(type, auditParams, auditRef);
    if (res) {
      messageC(res.msg, "success");
      emits("success");
    }
  } catch (error) {}
};

//回显
const getHx = async () => {
  const result = await ApplicantApi.query(attrs.keyid);
  if (result.code == 0) {
    // let timeStr = '';
    form.value.timeRange = ["0", "1"];
    for (let key in result.data) {
      if (key == "appendix") {
        form.value["appendixSaveVOList"] = result.data[key];
      } else if (key == "admTMeetuserList") {
        form.value["admTMeetuserList"] = result.data[key];
        let arr = result.data[key];
        form.value.chry = arr.map((i) => i.fkuserid);
      } else if (key == "meetservice") {
        if (result.data[key]) {
          form.value["meetserviceArr"] = result.data[key].split(",");
        }
      } else if (key == "starttime") {
        if (result.data[key]) {
          form.value.timeRange[0] = dayjs(result.data[key]).format("YYYY-MM-DD HH:mm");
        }
      } else if (key == "endtime") {
        if (result.data[key]) {
          form.value.timeRange[1] = dayjs(result.data[key]).format("YYYY-MM-DD HH:mm");
        }
      } else if (key == "ismessage" || key == "isincharge") {
        form.value[key] = result.data[key] + "";
      } else {
        form.value[key] = result.data[key];
      }
    }
  }
};

// 弹窗关闭
const dialogClose = () => {
  if (formRef.value) {
    formRef.value.form.resetFields();
  }
  form.value = {};
  form.value.timeRange = [];
  form.value.appendixSaveVOList = [];
};

watch(
  () => attrs.open,
  async (val, nva) => {
    if (val) {
      try {
        await getMeetServe();
      } catch (error) {}

      form.value.convenor = userInfo.value["name"];
      form.value.phone = userInfo.value["tel"] || "";
      form.value.convenorid = userInfo.value["userId"];
      form.value.status = 1;

      if (attrs.keyid != "") {
        await getHx();
      }
    }
  }
);

watch(
  () => form.value.timeRange,
  (val, nav) => {
    form.value.timeRange.map((item) => {
      item = dayjs(dayjs(item).valueOf()).format("YYYY-MM-DD HH:mm");
    });
    form.value.starttime = form.value.timeRange[0];
    form.value.endtime = form.value.timeRange[1];
  }
);

watch(
  () => form.value.chry,
  async () => {
    await getTree();
  }
);

watch(
  () => form.value.meetserviceArr,
  () => {
    if (form.value.meetserviceArr) {
      form.value.meetservice = form.value.meetserviceArr.join(",");
    }
  }
);
</script>

<style lang="scss"></style>
